package com.taxi.driver.module.main.mine.message;

import com.qianxx.utils.RxUtil;
import com.taxi.driver.R;
import com.taxi.driver.common.BasePresenter;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.module.vo.MessageVO;

import javax.inject.Inject;

public class MessagePresenter extends BasePresenter implements MessageContract.Presenter {

    private final MessageContract.View mView;
    private final UserRepository mUserRepository;

    private int nowPage = 1;

    @Inject
    public MessagePresenter(MessageContract.View view, UserRepository userRepository) {
        mView = view;
        mUserRepository = userRepository;
    }

    @Override
    public void refresh() {
        mSubscriptions.add(
                mUserRepository.getMsgList(1, 2)
                        .flatMapIterable(entities -> entities)
                        .map(MessageVO::createFrom)
                        .toList()
                        .compose(RxUtil.applySchedulers())
                        .doAfterTerminate(() -> nowPage = 2)
                        .subscribe(mView::setList,
                                ex -> showNetworkError(ex, R.string.network_error, mView)));
    }

    @Override
    public void loadMore() {
        mSubscriptions.add(
                mUserRepository.getMsgList(nowPage, 2)
                        .flatMapIterable(entities -> entities)
                        .map(MessageVO::createFrom)
                        .toList()
                        .compose(RxUtil.applySchedulers())
                        .doAfterTerminate(() -> nowPage++)
                        .subscribe(mView::appendList,
                                ex -> showNetworkError(ex, R.string.network_error, mView)));
    }

    @Override
    public void deleteAll() {
        mUserRepository.deleteAll()
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(false))
                .doAfterTerminate(mView::hideLoadingView)
                .subscribe(entity -> mView.deleteSuccess(),
                        ex -> showNetworkError(ex, R.string.network_error, mView, mUserRepository));
    }
}

